package rsj.netty.filterhandler;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.netty.codec.HttpJsonRequest;
import com.rlyy.aibase.netty.codec.HttpJsonResponse;
import com.rlyy.aibase.os.service.Link;
import com.rlyy.aibase.os.work.WorkFactory;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.helpers.JsonHelper;
import com.rlyy.aibase.view.type.OsType_Enum;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.rtsp.RtspResponseStatuses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
import rsj.api.Config;
import rsj.api.MainUtil;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author xuguoliang@rlyy.com
 * @date 2019/12/26 11:04
 * @description
 * @package ${PACKAGE}
 */
@ChannelHandler.Sharable
@Component
public class BusinessFullHandler extends SimpleChannelInboundHandler<HttpJsonRequest> {


    @Resource
    public ApplicationArguments arguments;

    @Autowired
    private Link baseLink;

    private static final Logger logger = LoggerFactory.getLogger(BusinessFullHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpJsonRequest req) throws Exception {

        HttpRequest request = req.getRequest();

        if (!HttpMethod.POST.equals(request.method())) {
            logger.error("BusinessFullHandler checked httpMethod failed : {}", request.method());
            // this.sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); // 错误处理
            System.out.println("BusinessFullHandler 错误处理");
        }
        String msgBody = req.getBody().toString();
        Object out = this.doBusiness(msgBody);
        logger.info("BusinessFullHandler netty doBusiness method return : {}", out);
        System.out.println("BusinessFullHandler 执行结果为： " + out.toString());
        ChannelFuture future = ctx.writeAndFlush(new HttpJsonResponse(null, out));
        if (!HttpUtil.isKeepAlive(request)) {
            future.addListener(future1 -> ctx.close());
        }
    }




    protected Object doBusiness(String o) {
        Box in = JsonHelper.json2Box(o);
        Box box = execute(in);
        return box.toMap();
    }

    private static void notify100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, RtspResponseStatuses.CONTINUE);
        ctx.write(response);
    }


    public Box execute(Box input) {
        System.out.println("in : " + input.toJson());
        if (WorkFactory.getStatus() != OsType_Enum.RUN.getOsType()) {
            WorkFactory.start(Config.class.getName());
        }
        return baseLink.excute(input);
    }





    public static int runPort = 9090;
    /**
     * 文件名为KEY 文件绝对路径为VALUE
     */
    private static final HashMap<String, String> confFilesPath = new HashMap<>();

    private static void parseTwoParamConf(String[] args) {
        String arg0 = args[0];
        String arg1 = args[1];
        if (!new File(arg0).exists()) {
            throw new IllegalArgumentException("第一个配置参数只能是配置文件或配置文件路径，配置文件不存在！");
        }
        if (!isInteger(arg1)) {
            throw new IllegalArgumentException("第二个配置参数只能是端口号！");
        }

        loadConfByFileAbsoluPath(arg0);
        runPort = Integer.parseInt(arg1);
    }

    private static void loadConfByFileAbsoluPath(String arg1) {
        confFilesPath.clear();
        List<File> allDirectoryFiles = MainUtil.getAllDirectoryFiles(arg1);
        if (allDirectoryFiles.size() == 0) {
            logger.error("------------------配置文件目录下没有配置文件------------------");
        }
        allDirectoryFiles.forEach(file -> {
            confFilesPath.put(file.getName(), file.getAbsolutePath());
        });
        logger.error("confFilesPathMap:{}", JSON.toJSONString(confFilesPath));
    }

    public static String getConfResource(String confFileKey) {
        return confFilesPath.get(confFileKey);
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}
